package searchteam.client.ui.widgets;

import java.util.ArrayList;

import searchteam.client.beansMirrors.TeamMirror;
import searchteam.client.services.SearchTeamServices;
import searchteam.client.services.SearchTeamServicesAsync;
import searchteam.client.ui.SearchTeamUI;
import searchteam.client.ui.callbacks.getAllTeamsCallback;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.ListBox;

public class TeamListBox extends ListBox implements Display {
	
	private ArrayList<TeamMirror> teams;
	private boolean thereIsAFirstItem;
	private boolean thereIsATeamToSelect;
	private String firstItem;
	private TeamMirror teamToSelect;
	
	SearchTeamServicesAsync services = GWT.create(SearchTeamServices.class);
	
	public TeamListBox() {
		thereIsAFirstItem = false;
		thereIsATeamToSelect = false;
		teams = new ArrayList<TeamMirror>();
		this.setVisibleItemCount(1);
		
		services.getAllTeams(new getAllTeamsCallback(this));
	}
	
	public TeamListBox(String first) {
		thereIsAFirstItem = true;
		thereIsATeamToSelect = false;
		firstItem = first;
		teams = new ArrayList<TeamMirror>();
		this.setVisibleItemCount(1);
		this.addItem(firstItem);
		
		services.getAllTeams(new getAllTeamsCallback(this));
	}
	
	public TeamListBox(TeamMirror mirror) {
		thereIsAFirstItem = false;
		thereIsATeamToSelect = true;
		teamToSelect = mirror;
		teams = new ArrayList<TeamMirror>();
		this.setVisibleItemCount(1);
		
		services.getAllTeams(new getAllTeamsCallback(this));
	}
	
	public TeamListBox(String first, TeamMirror mirror) {
		thereIsAFirstItem = true;
		thereIsATeamToSelect = true;
		firstItem = first;
		teamToSelect = mirror;
		teams = new ArrayList<TeamMirror>();
		this.setVisibleItemCount(1);
		this.addItem(firstItem);
		
		services.getAllTeams(new getAllTeamsCallback(this));
	}

	public void addMirror(MirrorDisplay mirror) {
		teams.add(((TeamMirrorDisplay)mirror).getBean());
		this.addItem(mirror.getText());
		if(thereIsATeamToSelect && mirror.getId() == teamToSelect.getId()) {
			this.setSelectedIndex(this.getItemCount() - 1);
		}
	}

	public void clearMirrors() {
		teams.clear();
		this.clear();
		if(thereIsAFirstItem) {
			this.addItem(firstItem);
		}
	}

	public SearchTeamUI getMainUI() {
		return null;
	}
	
	public TeamMirror getSelectedTeam() {
		if(thereIsAFirstItem) {
			if(this.getSelectedIndex() == 0)
				return null;
			else
				return teams.get(this.getSelectedIndex() - 1);
		}
		else {
			return teams.get(this.getSelectedIndex());
		}
	}

}
